package com.platform.service.impl;

import com.platform.annotation.SysLog;
import com.platform.base.BaseService;
import com.platform.common.Const;
import com.platform.common.ServerResponse;
import com.platform.dao.RoleMenuMapper;
import com.platform.pojo.Menu;
import com.platform.pojo.RoleMenu;
import com.platform.service.IRoleMenuService;
import com.platform.util.NumberUtil;
import com.platform.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

@Service("iRoleMenuService")
public class RoleMenuServiceImpl extends BaseService implements IRoleMenuService {



    @SysLog("新增角色菜单")
    public ServerResponse<String> insert(RoleMenu roleMenu){
        int countResult = roleMenuMapper.insert(roleMenu);
        if(countResult > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SAVEERROR);
    }

    @SysLog("删除角色菜单")
    public ServerResponse<String> del(Integer id){
        int countResult = roleMenuMapper.deleteByPrimaryKey(id);
        if(countResult > 0){
            return ServerResponse.createBySuccessMessage(Const.Msg.DELSUCCESS);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.DELERROR);
    }

    @SysLog("查询角色编码已有菜单权限")
    public ServerResponse<List<Integer>> selectByRoleCode(String roleCode){
        List<Integer> integerList = roleMenuMapper.selectByRoleCode(roleCode);
        if(null != integerList && 0 < integerList.size()){
            return ServerResponse.createBySuccess(Const.Msg.SELECTSUCCESS,integerList);
        }
        return ServerResponse.createByErrorMessage(Const.Msg.SELECTERROR);
    }

    /**
     * 保存角色菜单
     * @param roleCode
     * @param menuIdArr
     * @return
     */
    @SysLog("菜单权限编辑之保存角色菜单")
    @Override
    public ServerResponse<String> addRoleMenu(String roleCode, String menuIdArr) {
        //先删除角色所有菜单权限
        roleMenuMapper.delByRoleCode(roleCode);
        int resultCount = 0;
        if(StringUtil.isNotEmpty(menuIdArr)){
            //分割菜单集合
            String[] ids = menuIdArr.replaceAll("，",",").split(",");
            if(null != ids && 0 < ids.length){
                for (int i = 0; i <ids.length ; i++) {
                    //循环保存角色菜单
                    RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setRoleCode(roleCode);
                    roleMenu.setMenuId(NumberUtil.safeToNumber(ids[i]));
                    if(roleMenuMapper.insert(roleMenu)> 0){
                        resultCount++;
                    }
                }
            }
        }
        return ServerResponse.createBySuccessMessage(Const.Msg.SAVESUCCESS);
    }
}
